package com.zs.main.config;

import com.zs.common.annotation.ApiMonitor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Copyright 2020 ZS Network Co., Ltd. All rights reserved.
 * 本文件仅限于正数网络技术有限公司内部传阅，禁止外泄以及用于其他的商业目的。
 *
 * @Author quanming
 * @Date 2021/8/25 16:51
 * @Desc
 */
@Component
public class InitializingApiMonitorConfiguration extends AbstractInitializingConfig implements InitializingBean{

    @Value("${server.servlet.context-path:}")
    private String contextPath;

    public static Map<String,String> apiMonitorCache = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(ApiMonitor.class);
        for (Map.Entry<String, Object> next : beansWithAnnotation.entrySet()) {
            Class<?> aClass = Class.forName(StringUtils.substringBefore(next.getValue().toString(), "@"));
            RequestMapping requestMappingAno = aClass.getAnnotation(RequestMapping.class);
            String prefixPath;
            if (Objects.nonNull(requestMappingAno)) {
                String requestMapping = super.getRequestMapping(requestMappingAno.value());
                prefixPath = contextPath + requestMapping;
            } else {
                prefixPath = contextPath;
            }

            Method[] methods = aClass.getMethods();
            for (Method method : methods) {
                String requestMapping = super.handleRequestMapping(prefixPath, method, ApiMonitor.class);
                if (StringUtils.isNotBlank(requestMapping)) {
                    apiMonitorCache.put(requestMapping, method.getAnnotation(ApiMonitor.class).name());
                }
            }
        }
    }

}
